package info.webest.media.headset;

import info.webest.media.Options;
import info.webest.media.activities.MainActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;

// http://stackoverflow.com/questions/2524923/issues-with-action-headset-plug-broadcast-in-android
// Code in onCreate of main Activity: Register receiver
// 
// this.registerReceiver(new BroadcastsHandler(), new IntentFilter(Intent.ACTION_HEADSET_PLUG));

public class HeadsetPlugReceiver extends BroadcastReceiver {

	// ACTION_HEADSET_PLUG
	// state - 0 for unplugged, 1 for plugged.
	// name - Headset type, human readable string
	// microphone - 1 if headset has a microphone, 0 otherwise

	@Override
	public void onReceive(Context context, Intent intent) {

		String action = intent.getAction();

		if (action.equalsIgnoreCase(Intent.ACTION_HEADSET_PLUG)) {
			// String data = intent.getDataString();
			// Bundle extraData = intent.getExtras();

			int state = intent.getIntExtra("state", -1);
			// String nm = intent.getStringExtra("name");
			// int mic = intent.getIntExtra("microphone", -1);

			switch (state) {
			case 0:
				if (Options.HeadsetUnplug) {
					MainActivity.getInstance().stopSong();
				}
				break;

			case 1:
				if (Options.HeadsetPlug) {
					MainActivity.getInstance().playSong();
				}
				
				// HEADSET MEDIA BUTTON
				if (Options.HeadsetButton) {
					AudioManager audioManager = (AudioManager) MainActivity
							.getInstance().getSystemService(
									android.content.Context.AUDIO_SERVICE);
					audioManager
							.registerMediaButtonEventReceiver(new ComponentName(
									MainActivity.getInstance().getPackageName(),
									HeadsetButtonReceiver.class.getName()));
				}
				break;
			}

			// DebugAlert(context, st, nm, mic);
		}
	}

	// private void DebugAlert(Context context, int st, String nm, int mic){
	// String all = "state: " + (st == 1 ? "on" : "off") + " ("
	// + Integer.toString(st) + "), name: " + nm
	// + ", microphone: " + (st == 1 ? "yes" : "no") + " ("
	// + Integer.toString(mic) + ")";

	// AlertDialog.Builder builder = new AlertDialog.Builder(context);
	// builder.setTitle("Headset broadcast");
	// builder.setMessage(all);
	// builder.setPositiveButton("Okey-dokey",
	// new DialogInterface.OnClickListener() {

	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// }
	// });
	// builder.create().show();

	// }
}